package me.dwliu.ebase.modules.gen.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.dwliu.ebase.modules.gen.entity.ColumnEntity;
import me.dwliu.ebase.modules.gen.entity.TableEntity;
import me.dwliu.ebase.modules.gen.mapper.GenMapper;
import me.dwliu.ebase.modules.gen.util.PageUtils;
import me.dwliu.ebase.modules.gen.util.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成工具服务层
 *
 * @author liudw
 * @create 2018-03-27 17:44
 **/
@Service
public class SysGenService {
    @Autowired
    private GenMapper genMapper;
    @Autowired
    private CodeGenService codeGenService;

    /**
     * 查询数据库表列表
     *
     * @param query
     * @return
     */
    public PageUtils queryList(Query query) {

        Page<?> page = PageHelper.startPage(query.getPage(), query.getLimit());

        List<TableEntity> lists = genMapper.queryList(query);

        return new PageUtils(lists, (int) page.getTotal(), query.getLimit(), query.getPage());
    }


    public TableEntity queryTable(String tableName) {
        return genMapper.queryTable(tableName);
    }


    public List<ColumnEntity> queryColumns(String tableName) {
        return genMapper.queryColumns(tableName);
    }


    public byte[] genCode(String[] tableNames) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        for (String tableName : tableNames) {
            TableEntity table = genMapper.queryTable(tableName);
            List<ColumnEntity> columns = genMapper.queryColumns(tableName);

            try {
                codeGenService.generatorCode(table, columns, zipOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //IOUtils.closeQuietly(zipOutputStream);

        return byteArrayOutputStream.toByteArray();

    }

    public List<Map<String, String>> previewTemplateCode(String tableName) {
        TableEntity table = genMapper.queryTable(tableName);
        List<ColumnEntity> columns = genMapper.queryColumns(tableName);
        return codeGenService.previewTemplateCode(table, columns);
    }
}
